<?php
/**
*数据库处理类
*/

/*test*/
$db = new Database(array('host'=>'localhost','username'=>'root','password'=>'123456','db'=>'ci_test'));
$sql = "select username from member where id=1";
$m1 = $db->query($sql);
// print_r($m1);die();
$wo = $db->fetchOne('id=1','member','username');
// print_r($wo);
$tt = $db->fetchOne('uid=3','teacher','*');
print_r($tt);
class Database
{
	private $dbsource;
	private $_host;
	private $_port;
	private $_username;
	private $_password;
	private $_db;
	
	private $_pconnect = TRUE;

	public function __construct($param){
		$this->_host = $param['host'];
		$this->_port = $param['port'];
		$this->_username = $param['username'];
		$this->_password = $param['password'];

		$this->_db = $param['db'];

		$this->_pconnect = $param['pconnect'];
		if($this->_pconnect == TRUE){
			$this->dbsource = mysql_pconnect($this->_host, $this->_username, $this->_password);
		} else {
			$this->dbsource = mysql_connect($this->_host, $this->_username, $this->_password);
		}
		/*不能连接时*/
		if(! $this->dbsource){
			//...
			die(' cannot connect ');
		}		 
		mysql_select_db($this->_db);
		
	}

	public function query($sql){
		return mysql_query($sql);
	}

	public function fetchOne( $conditions, $tables, $fields='*'){
		$sql = " SELECT " . $fields ;
		$sql .= " FROM ";
		if($tables){
			$sql .= $tables;
		}else{
			return FALSE;
		}
		if($conditions){
			$sql .= " WHERE 1=1 AND ". $conditions;
		}
		$sql .= " LIMIT 1 ";
		$query = $this->query($sql);
		$arr = array();
		while ($row = mysql_fetch_object($query)) {
			array_push($arr, $row);
		}
		//返回第一个
		return $arr[0] ;
		
	}
	/**
	* 查找多个
	*/
	public function fetchAll( $conditions, $tables, $fields='*', $sort = NULL, $limit = 10){
		$sql = "SELECT $fields FROM ";
		if($tables){
			$sql .= $tables;
		}else{
			return FALSE;
		}
		if($conditions != NULL){
			$sql .= " WHERE 1=1 AND ".$conditions;
		}
		if($sort != NULL){
			$sql .= " ORDER BY ".$sort;
		}
		$sql .= " LIMIT ".$limit;
		$query = $this->query($sql);
		$arr = array();

		while ($row = mysql_fetch_object($query)) {
			array_push($arr, $row);
		}
		return $arr;
	}

}